package com.ldr.custom.spring.v3.aop.intercept;

import com.ldr.custom.spring.v3.aop.GPJoinPoint;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public abstract class GPAbstractAspectAdvice {

    private Method aspectMethod;
    private Object aspectTarget;

    public GPAbstractAspectAdvice(Method aspectMethod, Object aspectTarget) {
        this.aspectMethod = aspectMethod;
        this.aspectTarget = aspectTarget;
    }


    protected Object invokeAdviceMethod(GPJoinPoint joinPoint, Object returnValue, Throwable tx) throws InvocationTargetException, IllegalAccessException {

        Class<?>[] parameterTypes = this.aspectMethod.getParameterTypes();

        if (null == parameterTypes || parameterTypes.length == 0) {
           return this.aspectMethod.invoke(this.aspectTarget);
        } else {

            Object[] args = new Object[parameterTypes.length];
            for (int i = 0; i < parameterTypes.length; i++) {
                if (parameterTypes[i] == GPJoinPoint.class) {
                    args[i] = joinPoint;
                } else if (parameterTypes[i]==Throwable.class){
                    args[i]=tx;
                }else if (parameterTypes[i]==Object.class){
                    args[i]=returnValue;
                }
            }
           return this.aspectMethod.invoke(aspectTarget,args);
        }
    }


}
